<?php
/**
 *CustomerRepositories
 * @author tan bing
 * @date 2021-07-19 12:59
 */


namespace Modules\Coupon\Repositories\Eloquent;


use Modules\Coupon\Entities\Coupon;
use Modules\Coupon\Entities\UserCoupon;
use Modules\Coupon\Repositories\Contracts\CouponInterface;

class CouponRepositories implements CouponInterface
{

    public function findById($id)
    {
        return Coupon::find($id);
    }

    public function getPageData($param, $perPage)
    {
        return Coupon::addWhere($param)->paginate(!empty($param['limit']) ? $param['limit'] : $perPage);
    }

    public function getCouponList($param)
    {
        return Coupon::addWhere($param)->get();
    }

    public function addAndEditDetail($data)
    {
        if(!empty($data['id'])) {
            $couponModel = Coupon::find($data['id']);
            if(!$couponModel) {
                $couponModel = new Coupon();
            }
        } else {
            $couponModel = new Coupon();
        }

        $couponModel->status       = $data['status'];
        $couponModel->index_status = $data['index_status'];
        $couponModel->coupon_name  = $data['coupon_name'];
        $couponModel->coupon_type  = $data['coupon_type'];
        $couponModel->reduce_price = $data['reduce_price'];
        $couponModel->discount     = $data['discount'];
        $couponModel->min_price    = $data['min_price'];
        $couponModel->expire_type  = $data['expire_type'];
        if($data['expire_type'] == 2) {
            $couponModel->start_time   = strtotime($data['start_time']);
            $couponModel->end_time     = strtotime($data['end_time']);
        }
        $couponModel->expire_day   = $data['expire_day'];
        $couponModel->apply_range  = $data['apply_range'];
        $couponModel->total_num    = $data['total_num'];
        $couponModel->sort         = $data['sort'];
        $data['describe'] && $couponModel->describe = $data['describe'];
        !empty($data['apply_range_config']) && $couponModel->apply_range_config = json_encode($data['apply_range_config']);

        if(!$couponModel->save()) throw new \Exception('添加或编辑失败，请重试');

        return $couponModel;
    }

    /**
     * @param $param
     * @param null $perPage
     * @return mixed
     * @author tan bing
     * @date 2021-09-16 14:44
     */
    public function getUserCouponList($param, $perPage = null)
    {
        $where = [];
        if(!empty($param['nickname'])) {
            $where[] = ['users.nickname', 'like', $param['nickname'] . '%'];
        }
        return UserCoupon::addWhere($param)
            ->leftJoin('Users', 'users.id', '=', 'user_coupon.user_id')
            ->where($where)
            ->select('user_coupon.*', 'users.nickname', 'users.avatar', 'users.id')
            ->orderBy('created_at', 'desc')
            ->paginate(!empty($param['limit']) ? $param['limit'] : $perPage);
    }
}